<?php

namespace app\admin\service;

use app\model\ConfigModel;
use PhpOffice\PhpWord\Exception\CopyFileException;
use PhpOffice\PhpWord\Exception\CreateTemporaryFileException;
use PhpOffice\PhpWord\Exception\Exception;
use PhpOffice\PhpWord\TemplateProcessor;
use think\facade\Log;
use think\Service;

class EchartsService extends Service
{
    /**
     * 生成医院简版word报告
     * @param array $data
     * @param $FactorScoreField
     * @return array
     * @throws CopyFileException
     * @throws CreateTemporaryFileException
     */
    public function HospitalWord(array $data, $FactorScoreField): array
    {
        $templateProcessor = new TemplateProcessor(app()->getRootPath() . 'public/export_template/hospital.docx');
        // 定位并修改内容部分
        $templateProcessor->setValue('nickname', $data['user_name'] ?? '--'); // 替换模板中的变量
        $templateProcessor->setValue('sex', $data['sex'] == 1 ? '男' : '女'); // 替换模板中的变量
        $templateProcessor->setValue('age', $data['age'] ?? '--'); // 替换模板中的变量
        $templateProcessor->setValue('phone', $data['phone'] ?? '--'); // 替换模板中的变量
        $templateProcessor->setValue('username', $data['username'] ?? '--'); // 替换模板中的变量
        $templateProcessor->setValue('finish_time', gmdate('H:i:s',$data['finish_used_time']??0)); // 替换模板中的变量
        $templateProcessor->setValue('rating_scale_name', $data['rating_scale_name'] ?? '--'); // 替换模板中的变量

        if (!empty($data[$FactorScoreField])) {
            $templateProcessor->cloneBlock('result_block_two', count($data[$FactorScoreField]), true, true);
            foreach ($data[$FactorScoreField] as $key => $value) {
                $index = $key + 1;
                $templateProcessor->setValue('factor_name#' . $index, $value['factor_name']);
                $templateProcessor->setValue('score#' . $index, $value['score']);
                $templateProcessor->setValue('result#' . $index, $value['overview']);
            }
        }

        $templateProcessor->setValue('create_time', $data['time'] ? date('Y-m-d H:i:s', $data['time']) : '--'); // 替换模板中的变量
        $templateProcessor->setValue('dname', '--'); // 替换模板中的变量
        // 保存修改后的文档
        $ext = '.docx';
        $save_name = '/export/hospital' . date('Ym') . '/' . date('d') . '_' . time() . uniqid();
        $local_word = app()->getRootPath() . 'public' . $save_name . $ext;
        $file_path = dirname($local_word);
        folder_build($file_path);
        $templateProcessor->saveAs($local_word);
        switch (env('UPLOAD_TYPE')) {
            case 'local':
                WordToPdf($local_word);
                $word = $save_name . $ext;
                $pdf = $save_name . '.pdf';
                break;
            case 'oss':
                WordToPdf($local_word);
                // 上传到oss-word
                $upload = new \app\common\Upload();
                $upload = $upload->defaultConfig();
                $fileContent = file_get_contents($local_word);
                $word = $upload->upload($fileContent, 'binary', $ext);
                // 上传到oss-pdf
                $pdf = str_replace($ext, '', $local_word);
                $fileContent = file_get_contents($pdf . '.pdf');
                $pdf = $upload->upload($fileContent, 'binary', '.pdf');
                break;
            default:
                Log::channel('job')->error('生成报告上传报告配置错误！');
                return [
                    'word' => '',
                    'pdf' => '',
                ];
        }
        return [
            'word' => $word,
            'pdf' => $pdf,
        ];
    }

    /**
     * 生成word自我报告
     * @param array $data
     * @param $FactorScoreField
     * @return array
     * @throws CopyFileException
     * @throws CreateTemporaryFileException
     * @throws Exception
     */
    public function SelfWord(array $data, $FactorScoreField): array
    {
        $ConfigModel = new ConfigModel();
        $config = $ConfigModel->where([
            'unit_id' => $data['unit_id'],
            'key' => 'evaluation_report'
        ])->value('value') ?? '';
        $config = json_decode($config, true);
        if ($config['export_style'] == 1) {
            $templateProcessor = new TemplateProcessor(app()->getRootPath() . 'public/export_template/self.docx');
        } else {
            $templateProcessor = new TemplateProcessor(app()->getRootPath() . 'public/export_template/self2.docx');
        }
        // 定位并修改内容部分
        $templateProcessor->setValue('rating_scale_name', $data['rating_scale_name'] ?? ''); // 替换模板中的变量
        $templateProcessor->setValue('user_name', $data['user_name'] ?? ''); // 替换模板中的变量
        $templateProcessor->setValue('user_sex', $data['sex'] == 1 ? '男' : '女'); // 替换模板中的变量
        $templateProcessor->setValue('phone', $data['phone'] ?? ''); // 替换模板中的变量
        $templateProcessor->setValue('unit_name', $data['unit_name'] ?? ''); // 替换模板中的变量
        $templateProcessor->setValue('department_name', $data['department_name'] ?? ''); // 替换模板中的变量
        $templateProcessor->setValue('username', $data['username'] ?? ''); // 替换模板中的变量
        $templateProcessor->setValue('role_name', $data['role_name'] ?? ''); // 替换模板中的变量
        $templateProcessor->setValue('finish_used_time', gmdate('H:i:s',$data['finish_used_time']??0)); // 替换模板中的变量
        $templateProcessor->setValue('rating_scale_introduce', $data['rating_scale_introduce'] ?? ''); // 替换模板中的变量
        $all_warning_string = [];
        if (!empty($data[$FactorScoreField])) {
            $count = count($data[$FactorScoreField]);
            $templateProcessor->cloneRow('result_factor_name', $count);
            $templateProcessor->cloneBlock('result_block', $count, true, true);
            $templateProcessor->cloneBlock('result_block_three', $count, true, true);

            foreach ($data[$FactorScoreField] as $key => $value) {
                if ($value['is_warning'] == 1) {
                    $all_warning_string[] = $value['factor_name'];
                }

                $index = $key + 1;
                $templateProcessor->setValue('result_factor_name#' . $index, $value['factor_name']);
                $templateProcessor->setValue('result_score#' . $index, $value['score']);

                $factor_name_string = $value['factor_name'] == '症状自评量表SCL-90' ? $value['factor_name'] : $value['factor_name'] . '得分';
                $score_string = $value['factor_name'] == '症状自评量表SCL-90' ? $value['score'] . '项' : $value['score'] . '分';
                $templateProcessor->setValue('factor_name#' . $index, $factor_name_string);
                $templateProcessor->setValue('score#' . $index, $score_string);
                $templateProcessor->setValue('overview#' . $index, $value['overview']);
                $templateProcessor->setValue('explain#' . $index, $value['explain']);

                $templateProcessor->setValue('factor_name#' . $index, $value['factor_name']);
                if (!empty($value['rating_scale_factor_level'])) {
                    $templateProcessor->cloneRow('level_name#' . $index, count($value['rating_scale_factor_level']));
                    foreach ($value['rating_scale_factor_level'] as $k => $v) {
                        $index_k = $index . '#' . ($k + 1);
                        $templateProcessor->setValue('low_range#' . $index_k, $v['low_range']);
                        $templateProcessor->setValue('high_range#' . $index_k, $v['high_range']);
                        preg_match('/\（(.*?)\）/', $v['name'], $level_name);
                        $templateProcessor->setValue('level_name#' . $index_k, $level_name[1] ?? '');
                    }
                }
            }
        }

        $templateProcessor->setValue('warning_name', $data['warning_name']); // 替换模板中的变量
        $templateProcessor->setValue('warning', implode('、', $all_warning_string)); // 替换模板中的变量
        if (!empty($data['gaugeImg'])) {
            $templateProcessor->setImageValue('guage', ['path' => $data['gaugeImg'], 'width' => 360, 'height' => 360]);
        } else {
            $templateProcessor->setValue('guage', ''); // 替换模板中的变量
        }
        if (!empty($data['barImg'])) {
            $templateProcessor->setImageValue('bar', ['path' => $data['barImg'], 'width' => 600, 'height' => 300]);
        } else {
            $templateProcessor->setValue('bar', ''); // 替换模板中的变量
        }

        //页眉logo
        if (!empty($config['header_logo'])) {
            $templateProcessor->setImageValue('header_logo', ['path' => $config['header_logo'], 'width' => 350, 'height' => 35]);
        } else {
            $templateProcessor->setValue('header_logo', ''); // 替换模板中的变量
        }

        // 保存修改后的文档
        $ext = '.docx';
        $save_name = '/export/self' . date('Ym') . '/' . date('d') . '_' . time() . uniqid();
        $local_word = app()->getRootPath() . 'public' . $save_name . $ext;
        $file_path = dirname($local_word);
        folder_build($file_path);
        $templateProcessor->saveAs($local_word);
        switch (env('UPLOAD_TYPE')) {
            case 'local':
                WordToPdf($local_word);
                $word = $save_name . $ext;
                $pdf = $save_name . '.pdf';
                break;
            case 'oss':
                WordToPdf($local_word);
                // 上传到oss-word
                $upload = new \app\common\Upload();
                $upload = $upload->defaultConfig();
                $fileContent = file_get_contents($local_word);
                $word = $upload->upload($fileContent, 'binary', $ext);
                // 上传到oss-pdf
                $pdf = str_replace($ext, '', $local_word);
                $fileContent = file_get_contents($pdf . '.pdf');
                $pdf = $upload->upload($fileContent, 'binary', '.pdf');
                break;
            default:
                Log::channel('job')->error('生成报告上传报告配置错误！');
                return [
                    'word' => '',
                    'pdf' => '',
                ];
        }
        return [
            'word' => $word,
            'pdf' => $pdf,
        ];
    }

    /**
     * 生成word团体报告
     * @param array $data
     * @return array
     * @throws Exception
     */
    public function GroupReport(array $data): array
    {
        $is_group = 1;
        if (!empty($data['unit_id'])) {
            $ConfigModel = new ConfigModel();
            $config = $ConfigModel->where([
                'unit_id' => $data['unit_id'],
                'key' => 'evaluation_report'
            ])->value('value') ?? '';
            $config = json_decode($config, true);
            if (!empty($data['rating_scale_previous_name']) && in_array($data['rating_scale_previous_name'], [
                    '中小学生心理健康诊断测验(MHT)',
                    '小学生心理健康评定量表(MHRSP)',
                    '症状自评量表(SCL-90)',
                    '中小学生心理健康诊断测验（MHT）',
                    '小学生心理健康评定量表（MHRSP）',
                    '症状自评量表（SCL-90）',
                ])) {
                if ($config['export_style'] == 1) {
                    $templateProcessor = new TemplateProcessor(app()->getRootPath() . 'public/export_template/group_report.docx');
                } else {
                    $templateProcessor = new TemplateProcessor(app()->getRootPath() . 'public/export_template/group_report2.docx');
                }
            } else {
                $is_group = 0;
                if ($config['export_style'] == 1) {
                    $templateProcessor = new TemplateProcessor(app()->getRootPath() . 'public/export_template/not_group_report.docx');
                } else {
                    $templateProcessor = new TemplateProcessor(app()->getRootPath() . 'public/export_template/not_group_report2.docx');
                }
            }
        } else {
            if (!empty($data['rating_scale_previous_name']) && in_array($data['rating_scale_previous_name'], [
                    '中小学生心理健康诊断测验(MHT)',
                    '小学生心理健康评定量表(MHRSP)',
                    '症状自评量表(SCL-90)',
                    '中小学生心理健康诊断测验（MHT）',
                    '小学生心理健康评定量表（MHRSP）',
                    '症状自评量表（SCL-90）',
                ])) {
                $templateProcessor = new TemplateProcessor(app()->getRootPath() . 'public/export_template/group_report.docx');
            } else {
                $is_group = 0;
                $templateProcessor = new TemplateProcessor(app()->getRootPath() . 'public/export_template/not_group_report.docx');
            }
        }
        $upload = new \app\common\Upload();
        // 设置上传类型和文件大小
        $upload = $upload->defaultConfig();
        // 定位并修改内容部分
        $templateProcessor->setValue('rating_scale_name', $data['rating_scale_name'] . ' '); // 替换模板中的变量
        $templateProcessor->setValue('unit_name', $data['unit_name'] . ' '); // 替换模板中的变量
        $templateProcessor->setValue('rating_scale_introduce', $data['rating_scale_introduce'] . ' '); // 替换模板中的变量
        $templateProcessor->setValue('task_start_time', $data['task_start_time'] . ' '); // 替换模板中的变量
        $templateProcessor->setValue('task_end_time', $data['task_end_time'] . ' '); // 替换模板中的变量
        $templateProcessor->setValue('target_num', $data['target_num'] . ' '); // 替换模板中的变量
        $templateProcessor->setValue('total_complete_rate', $data['total_complete_rate'] . ' '); // 替换模板中的变量
        $templateProcessor->setValue('part_object', $data['part_object'] . ' '); // 替换模板中的变量
        $templateProcessor->setValue('involved_num', $data['involved_num'] . ' '); // 替换模板中的变量
        $templateProcessor->setValue('part_rate', $data['part_rate'] . ' '); // 替换模板中的变量
        $templateProcessor->setValue('involved_boy_num', $data['involved_boy_num'] . ' '); // 替换模板中的变量
        $templateProcessor->setValue('involved_girl_num', $data['involved_girl_num'] . ' '); // 替换模板中的变量
        $templateProcessor->setValue('not_involved_num', $data['not_involved_num'] . ' '); // 替换模板中的变量
        $templateProcessor->setValue('unpart_rate', $data['unpart_rate'] . ' '); // 替换模板中的变量
        $templateProcessor->setValue('not_involved_boy_num', $data['not_involved_boy_num'] . ' '); // 替换模板中的变量
        $templateProcessor->setValue('not_involved_girl_num', $data['not_involved_girl_num'] . ' '); // 替换模板中的变量
        $templateProcessor->setValue('user_answer_num', $data['user_answer_num'] . ' '); // 替换模板中的变量
        $templateProcessor->setValue('self_answer_rate', $data['self_answer_rate'] . ' '); // 替换模板中的变量
        $templateProcessor->setValue('involved_num', $data['involved_num'] . ' '); // 替换模板中的变量
        $templateProcessor->setValue('normal_report_num', ' ' . $data['normal_report_num'] . ' '); // 替换模板中的变量
        $templateProcessor->setValue('normal_report_rate', $data['normal_report_rate'] . ' '); // 替换模板中的变量
        $templateProcessor->setValue('invalid_report_num', ' ' . $data['invalid_report_num'] . ' '); // 替换模板中的变量
        $templateProcessor->setValue('invalid_report_rate', $data['invalid_report_rate'] . ' '); // 替换模板中的变量
        $templateProcessor->setValue('warning_report_num', $data['warning_report_num'] . ' '); // 替换模板中的变量
        $templateProcessor->setValue('warning_report_rate', $data['warning_report_rate'] . ' '); // 替换模板中的变量
        $templateProcessor->setValue('warning_report_boy_num', $data['warning_report_boy_num'] . ' '); // 替换模板中的变量
        $templateProcessor->setValue('warning_report_boy_rate', $data['warning_report_boy_rate'] . ' '); // 替换模板中的变量
        $templateProcessor->setValue('warning_report_girl_num', $data['warning_report_girl_num'] . ' '); // 替换模板中的变量
        $templateProcessor->setValue('warning_report_girl_rate', $data['warning_report_girl_rate'] . ' '); // 替换模板中的变量
        if (!empty($data['report_total_chart'])) {
            $img = $upload->upload($data['report_total_chart'], 'base64', '.png');
            $templateProcessor->setImageValue('peopleBar', ['path' => $img, 'width' => 550, 'height' => 280]);
        } else {
            $templateProcessor->setValue('peopleBar', ''); // 替换模板中的变量
        }
        if (!empty($data['reportPie1'])) {
            $img = $upload->upload($data['reportPie1'], 'base64', '.png');
            $templateProcessor->setImageValue('reportPie1', ['path' => $img, 'width' => 550, 'height' => 280]);
        } else {
            $templateProcessor->setValue('reportPie1', ''); // 替换模板中的变量
        }
        if (!empty($data['reportPie2'])) {
            $img = $upload->upload($data['reportPie2'], 'base64', '.png');
            $templateProcessor->setImageValue('reportPie2', ['path' => $img, 'width' => 550, 'height' => 280]);
        } else {
            $templateProcessor->setValue('reportPie2', ''); // 替换模板中的变量
        }

        $templateProcessor->cloneBlock('warning_report_level', count($data['warning_report_level']), true, true);
        foreach ($data['warning_report_level'] as $key => $value) {
            $index = $key + 1;
            $templateProcessor->setValue('name#' . $index, $value['name'] ?? ' ');
            $templateProcessor->setValue('num#' . $index, $value['num'] ?? '0 ');
            $templateProcessor->setValue('rate#' . $index, $value['rate'] ?? '0 ');
            $templateProcessor->setValue('boy#' . $index, $value['boy'] ?? '0 ');
            $templateProcessor->setValue('girl#' . $index, $value['girl'] ?? '0 ');
        }

        $templateProcessor->setValue('mode_name', $data['mode_name']); // 替换模板中的变量
        $templateProcessor->setValue('lowest_overall_score', $data['lowest_overall_score'] . ' '); // 替换模板中的变量
        $templateProcessor->setValue('highest_overall_score', $data['highest_overall_score'] . ' '); // 替换模板中的变量
        $templateProcessor->setValue('overall_average_score', $data['overall_average_score']) . ' '; // 替换模板中的变量

        $templateProcessor->setValue('lowest_report_score', $data['lowest_report_score'] . ' '); // 替换模板中的变量
        $templateProcessor->setValue('highest_report_score', $data['highest_report_score'] . ' '); // 替换模板中的变量
        $templateProcessor->setValue('overall_report_score', $data['overall_report_score'] . ' '); // 替换模板中的变量

        $templateProcessor->setValue('lowest_warning_factor', $data['lowest_warning_factor'] ? round($data['lowest_warning_factor'], 2) : '0.00'); // 替换模板中的变量
        $templateProcessor->setValue('highest_warning_factor', $data['highest_warning_factor'] ? round($data['highest_warning_factor'], 2) : '0.00'); // 替换模板中的变量
        $templateProcessor->setValue('overall_warning_factor', $data['overall_warning_factor'] ? round($data['overall_warning_factor'], 2) : '0.00'); // 替换模板中的变量

        $templateProcessor->setValue('WarningFactorArrayName', $data['WarningFactorArrayName']); // 替换模板中的变量

        $templateProcessor->setValue('factor_num', count($data['other_factor_result'] ?? []) + 1); // 替换模板中的变量

        if ($is_group) {
            $templateProcessor->cloneBlock('FactorInfo', count($data['other_factor_result']), true, true);
            foreach ($data['other_factor_result'] as $key => $value) {
                $index = $key + 1;
                $templateProcessor->setValue('name#' . $index, $value['name']);
                $templateProcessor->setValue('factor_explain#' . $index, $value['factor_explain']);
                $templateProcessor->setValue('involved_num#' . $index, $value['involved_num'] . ' ');
                $templateProcessor->setValue('min#' . $index, $value['min'] . ' ');
                $templateProcessor->setValue('max#' . $index, $value['max'] . ' ');
                $templateProcessor->setValue('average#' . $index, $value['average'] . ' ');
                $templateProcessor->setValue('normal#' . $index, $value['normal'] . ' ');
                $templateProcessor->setValue('normal_rate#' . $index, $value['normal_rate'] . ' ');

                $templateProcessor->cloneRow('warning_arr_name#' . $index, count($value['warning_arr']));
                foreach ($value['warning_arr'] as $k => $v) {
                    $index_k = $index . '#' . ($k + 1);
                    $templateProcessor->setValue('warning_arr_name#' . $index_k, $v['name']);
                    $templateProcessor->setValue('warning_arr_num#' . $index_k, $v['num'] . ' ');
                    $templateProcessor->setValue('warning_arr_warning_rate#' . $index_k, $v['warning_rate'] . ' ');
                }
                if (!empty($value['exception_bar_chart'])) {
                    $img = $upload->upload($value['exception_bar_chart'], 'base64', '.png');
                    $templateProcessor->setImageValue('exception_bar_chart#' . $index, ['path' => $img, 'width' => 550, 'height' => 280]);
                } else {
                    $templateProcessor->setValue('exception_bar_chart#' . $index, ''); // 替换模板中的变量
                }
                if (!empty($value['exception_pie_chart'])) {
                    $img = $upload->upload($value['exception_pie_chart'], 'base64', '.png');
                    $templateProcessor->setImageValue('exception_pie_chart#' . $index, ['path' => $img, 'width' => 550, 'height' => 280]);
                } else {
                    $templateProcessor->setValue('exception_pie_chart#' . $index, ''); // 替换模板中的变量
                }
            }
        }
        if (!empty($data['sortChart'])) {
            $img = $upload->upload($data['sortChart'], 'base64', '.png');
            $templateProcessor->setImageValue('sortChart', ['path' => $img, 'width' => 550, 'height' => 280]);
        } else {
            $templateProcessor->setValue('sortChart', ''); // 替换模板中的变量
        }
        $templateProcessor->setValue('WarningFactorArrayName2', $data['WarningFactorArrayName'] ?? ''); // 替换模板中的变量
        // 保存修改后的文档
        $ext = '.docx';
        $save_name = '/export/group_report' . date('Ym') . '/' . date('d') . '_' . time() . uniqid();
        $file_path = dirname(app()->getRootPath() . 'public' . $save_name . $ext);
        folder_build($file_path);
        $templateProcessor->saveAs(app()->getRootPath() . 'public' . $save_name . $ext);
        $fileContent = file_get_contents(app()->getRootPath() . 'public' . $save_name . $ext);
        $word = $upload->upload($fileContent, 'binary', $ext, $save_name);
        return [
            'word' => $word
        ];
    }
}